<template>
	<view class="wrapper">
		<view class="outtop">
			<view class="topwrapper" :style="{paddingTop:statusBarHeight+'px'}">
				<text @click="goBack" class="wlIcon-fanhui1" :style="{position:'absolute',left:'30px',top:(statusBarHeight+10)+'px'}"></text>
				<view
					:style="{height:menuButtonHeight+'px',textAlign:'center',lineHeight:menuButtonHeight+'px',fontWeight:'bold'}">
					人人聚团购</view>
				<view class="addsearch" style="display:flex;align-items: center; justify-content: space-between;">
					<view class="addressSelect" style="min-width:160rpx;" @click="showCityPicker" :style="{height:menuButtonHeight+'px'}">
						<image src="/static/images/location.png" style="width:48rpx;height:48rpx;"></image>
						<view class="addres" style="color:#333">{{params.area}}</view>
					</view>
					<view class="search" style="flex:1;">
						<text class="wlIcon-sousuo1 text-bold" style="margin-right:10rpx" @click="handleSearch"></text>
						<input @confirm="confirm" :adjust-position="false" type="text" v-model="params.search"
							placeholder="搜索关键词" confirm-type="search"></input>
					</view>
				</view>		
			</view>
		</view>

		<view class="menuwrapper">
			<view class="menuitem" v-for="item in typeList" :key="item.id" @click="getshopgoodsbytype(item,0)">
				<image :src="config.cdnurl + item.img"></image>
				<view class="name">{{item.name}}</view>
			</view>

		</view>

		<view class="wmwrapper">
			<view class="left">
				<image src="/static/images/wm.png"></image>
				<view class="tag">爆款低价</view>
			</view>
			<view class="right">
				<view class="item">
					<image src="/static/images/food.png"></image>
					<view class="desc">
						<view class="title">商品标题</view>
						<view class="sm">甜蜜暖冬</view>
						<view class="pricewrapper">
							<view class="price">￥819.8</view>
							<view class="zk">7.0折</view>
						</view>
					</view>
				</view>
				<view class="item">
					<image src="/static/images/food.png"></image>
					<view class="desc">
						<view class="title">商品标题</view>
						<view class="sm">甜蜜暖冬</view>
						<view class="pricewrapper">
							<view class="price">￥891.8</view>
							<view class="zk">7.0折</view>
						</view>
					</view>
				</view>

			</view>

		</view>


		<view class="smallmenuwrapper">
			<view class="smallwrapper">
				<view class="smallitem" :class="{active:index == subindex && subindex !== ''}"
					v-for="(item,index) in subtypeList" :key="item.id" @click="getshopgoodsbytype(item,1)">{{item.name}}
				</view>
			</view>
		</view>

		<view class="guesswrapper">
			<view class="title">猜你喜欢</view>
			<view class="desc">智能推荐你感兴趣的优品</view>
		</view>

		<view class="listwrapper">
			<view class="itemwrapper" @click="handleShop(item.id)" v-for="item in shopgoodsList" :key="item.id">
				<image mode="aspectFill" class="pic" :src="item.gimage"></image>
				<view class="descwrapper">
					<view class="namewrapper">
						<view class="name">{{item.gtitle}}</view>
					</view>
					<view class="pricewrapper">
						<view class="price">￥{{item.price}}</view>
						<view class="oldprice"></view>
					</view>
				</view>
			</view>

		</view>


		<!--定位选择城市-->
		<mpvue-city-picker :themeColor="themeColor" ref="mpvueCityPicker" :pickerValueDefault="cityPickerValueDefault"
			@onConfirm="onConfirm">
		</mpvue-city-picker>
		
	
	
		<view class="wanlshop-shop-container__tabbar" :style="{ height: `${sys.tabbarHeight}px`, paddingBottom:`${sys.tabbarBottom}px` }">
			<view class="cu-bar tabbar">
				<view class="action" @tap="handleTabbar('/pages/find')">
					<view class="wlIcon-31shouye"></view>
					<view>主页</view>
				</view>
				<view class="action" @tap="handleTabbar('/pages/business')">
					<view class="wlIcon-dianpu"></view>
					<view>商城</view>
				</view>
				<view class="action" @tap="handleTabbar('/pages/local')">
					<view class="wlIcon-weizhi"></view>
					<view>本地生活</view>
				</view>
				<view class="action" @tap="handleTabbar('/pages/notice/notice')">
					<view class="wlIcon-xiaoxizhongxin"></view>
					<view>消息</view>
				</view>
				<view class="action" @tap="handleTabbar('/pages/user')">
					<view class="wlIcon-31wode"></view>
					<view>我的</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import mpvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker.vue'
	import config from "@/common/config/config.js"
	export default {
		components: {
			mpvueCityPicker,
		},
		data() {
			return {
				statusBarHeight: 0, //顶部高度，
				menuButtonHeight: 0, //胶囊按钮高度
				config,
				typeList: [], //头部的分类
				subtypeList: [], //子分类


				params: {
					province: "",
					city: "",
					area: "",
					search: ""
				},


				selectParentType: {},
				selectSubType: {},
				parentIndex: 0,
				subindex: "",

				//picker
				themeColor: '#007AFF',
				cityPickerValueDefault: [0, 0, 1],
				pickerText: '',

				shopgoodsList: [],
				page: 1,
				pageSize: 10,
				finished: false,



			}
		},

		async onLoad() {
			const sys = uni.getSystemInfoSync();
			this.wanlsys = {
				headTop: sys.statusBarHeight,
				windowWidth: sys.windowWidth,
				windowHeight: sys.windowHeight,
				windowBottom: 0
			};
			const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			this.menuButtonHeight = menuButtonInfo.height;
			this.statusBarHeight = menuButtonInfo.top;

			//获取上面的分类
			this.getTypes();

			await this.getAddress();

			this.initgetshopgoods();


		},

		methods: {
			
			handleTabbar(url){
				uni.switchTab({
					url:url
				})
			},
			

			handleShop(id) {
				//this.$wanlshop.to(`/pages/shop/index?id=${id}`);
				this.$wanlshop.to(`/pages/shop/product/list?shop_id=${id}`);
			},


			goBack(){
				uni.navigateBack({
					delta:1
				})
			},


			getTypes() {
				let that = this;
				uni.request({
					url: "/wanlshop/shop/tuangoutypes",
					success(res) {
						that.typeList = res.data.data;
						//找到数组中的第一个类别，再找它的子类
						if (that.typeList.length > 0) {
							let firstType = that.typeList[0];
							that.getsubtype(firstType.id);


						}
					}
				})
			},


			getsubtype(id) {
				let that = this;
				let params = {
					id
				};
				uni.request({
					url: "/wanlshop/shop/getsubtype",
					data: params,
					success(res1) {
						that.subtypeList = res1.data.data
					}
				})
			},


			initgetshopgoods() {
				let that = this;

				let params = {
					area: this.params.area
				}

				uni.request({
					url: "/wanlshop/shop/initgetshopgoodsbytype",
					data: params,
					success(res) {
						res.data.data.forEach(item=>{
							item.gtitle = item.gtitle.substring(0,10)
						})
						that.shopgoodsList = res.data.data
					}
				})

			},


			getshopgoodsbytype(item, tag) {
				//tag 0 表示点击的是主分类的  tag 1 表示点击的是子分类的
				if (tag == 0) {
					//此时要更换一下，下面的一排子分类
					this.getsubtype(item.id);
					this.selectParentType = item;
					this.parentIndex = this.typeList.findIndex(it => {
						return item.id == it.id;
					})
					this.selectSubType = {}
					this.subindex = "";
				} else {
					this.selectSubType = item;
					this.subindex = this.subtypeList.findIndex(it => {
						return item.id == it.id
					})
					console.log(this.subindex);
				}

				this.shopgoodsList = [];
				this.page = 1;
				this.finished = false;
				//通过分类找下面的 shopgoodslist
				this.getshopgoodsdata(item.id)
			},

			getshopgoodsdata(id) {
				if (this.finished) {
					return;
				}
				let that = this;

				let params = {
					area: this.params.area
				};
				//如果子分类有选中的， 测
				if (id) {
					params.id = id;
				}

				params.searchStr = this.params.search;

				uni.request({
					url: "/wanlshop/shop/getshopgoodsbytype",
					data: params,
					success(res) {
						if (that.shopgoodsList.length >= res.data.total) {
							that.finished = true;
						} else {
							res.data.data.forEach(item=>{
								item.gtitle = item.gtitle.substring(0,10)
							})
							that.shopgoodsList = that.shopgoodsList.concat(res.data.data);
							that.page++
						}
					}
				})
			},



			showCityPicker() {
				this.$refs.mpvueCityPicker.show()
			},
			//三级联动
			onConfirm(e) {
				this.pickerText = JSON.stringify(e)
				let arr = e.label.split("-");
				//this.sameCity.name = arr[arr.length - 1]

				this.params.province = arr[0]
				this.params.city = arr[1]
				this.params.area = arr[2];
				//当选择之后要更新数据
				this.page = 1;
				this.shopgoodsList = [];
				this.finished = false;

				this.getshopgoodsbytype(0)

			},

			confirm() {
				this.page = 1;
				this.shopgoodsList = [];
				this.finished = false;
				this.getshopgoodsbytype(0)
			},

			async getAddress() {
				let res = this.$store.state.common.addressData
				if (Object.keys(res).length !== 0) {
					this.params.province = res.address.province;
					this.params.city = res.address.city;
					this.params.area = res.address.district;
				} else {
					await this.getLocation()
				}
			},


			getLocation() {

				let that = this;

				//测试代码————————————————————————————————————————————————————————————————————————				


				if (config.test) {
					return new Promise((resolve, reject) => {

						if (Object.keys(this.$store.state.common.addressData).length > 0) {
							resolve("ok");
						}

						let add = {
							latitude: 32.1524,
							longitude: 111.372,
							address: {
								city: "襄阳市",
								citycode: "0710",
								country: "中国",
								district: "谷城县",
								province: "湖北省",
								towncode: "420625500000",
								township: "薤山林场",
								latitude: 32.1524,
								longitude: 111.372,
								street: "汉和路",
								address_reference: {
									street: {
										title: "仙人渡"
									}
								}

							}
						};

						this.$store.commit('common/setAddress', add);
						resolve("ok")
					})


				} else {

					return new Promise((resolve, reject) => {
						if (Object.keys(this.$store.state.common.addressData).length > 0) {
							resolve();
						}


						uni.getLocation({
							type: 'gcj02',
							geocode: true,
							isHighAccuracy: true,
							altitude: false,
							success: res => {
								const latitude = res.latitude;
								const longitude = res.longitude;
								// const latitude = 32.1637;
								// const longitude = 111.3922;
								// 以高德地图API为例			
								// 	const amapKey = '817dcdcf5e5a3c606f6f13d76d563e8a';
								// 	const url = `https://restapi.amap.com/v3/geocode/regeo?key=${amapKey}&location=${longitude},${latitude}`;

								// 	uni.request({
								// 		url: url,
								// 		success: (response) => {
								// 		  const address = response.data.regeocode.addressComponent;
								//			address.street="aaa"
								// 		  const addressData = {
								// 			address:address,
								// 			latitude:latitude,
								// 			longitude:longitude
								// 		  }
								// 		  this.$store.commit('common/setAddress', addressData);
								// 		  this.province = address.province;
								// 		  this.city = address.city;
								// 		  this.area = address.district;

								// 		}
								// 	});


								let qqmapsdk = new QQMapWX({
									key: '7LHBZ-JGG6W-72RR6-YDOJY-LNRCS-FVB55' //后端给的key
								})


								qqmapsdk.reverseGeocoder({
									location: {
										latitude,
										longitude
									},

									success: function(res) {

										let address = res.result.address_component;


										address.township = res.result.address_reference
											.town.title;
										address.address_reference = res.result
											.address_reference;
										try {
											address.neighborhoodname = res.result
												.address_reference.street
												.title ? res.result.address_reference
												.street.title : "";
											address.street = res.result.address_reference
												.street.title ? res.result
												.address_reference.street.title : "";
										} catch (err) {
											address.neighborhoodname = "";
											address.street = "";
										}



										address.neighborhood = address.neighborhoodname;
										const addressData = {
											address: address,
											latitude: latitude,
											longitude: longitude,
											township: address.township,
											neighborhood: {
												name: address.neighborhoodname
											}
										}

										that.province = address.province;
										that.city = address.city;
										that.area = address.district;

										/**
													   address: {
														   city: "襄阳市"
														   district: "老河口市"
														   latitude: 32.25981716579861
														   longitude: 111.72213433159722
														   nation: "中国"
														   neighborhood: Object
														   neighborhoodname: "汉和路"
														   province: "湖北省"
														   street: "汉和路"
														   street_number: ""
														   township: "仙人渡镇"   
													   }
						
													   */


										that.$store.commit('common/setAddress',
											addressData);
										resolve("ok")

									},
									fail: function(error) {
										reject(error)
										console.error(error);
									},
								})


							}
						});
					})

				}



				//测试代码————————————————————————————————————————————————————————————————————————

			}



		}
	}
</script>

<style lang="scss" scoped>
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background: #FFF5F5;
		padding-bottom:80rpx;

		.login {
			top: 0;
			left: 0;
			position: fixed;
			background: transparent;
			min-height: 100vh;
			width: 100vw;
			z-index: 10000;
		}

		.act {
			color: orangered;
		}

		.outtop {
			width: 100%;
			height: 240rpx;
			background: linear-gradient(to bottom, #FA6161, #FFF5F5);
			padding-left: 24rpx;
			padding-right: 24rpx;
			box-sizing: border-box;

			.topwrapper {
				box-sizing: border-box;

				.addressSelect {
					display: flex;
					justify-content: flex-start;
					align-items: flex-end;
					color: #fff;
					height:60rpx;
					
	
				}
			}

			.search {
				margin: 0 auto;
				margin-top: 30rpx;
				width: 700rpx;
				background: rgba(255, 255, 255, .3);
				border-radius: 30rpx;
				height: 60rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				color: #aaa;
				padding: 0 30rpx;
				box-sizing: border-box;
			}
		}


		.wanlshop-shop-container__tabbar{
			background-color: rgb(255, 255, 255);
			z-index: 998;
			width: 100%;
			position: fixed;
			bottom: 0;
		}
		.menuwrapper {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 10rpx 36rpx;
			box-sizing: border-box;
			flex-flow: row wrap;
			

			.menuitem {
				display: flex;
				flex-flow: column nowrap;
				align-items: center;
				width:25%;
				image {
					width: 80rpx;
					height: 80rpx;
					margin-bottom: 10rpx;
				}

				.name {
					color: #333333;
					font-size: 26rpx;
				}
			}
		}

		.wmwrapper {
			display: flex;
			width: 682rpx;
			height: 146rpx;
			background: #fff;
			margin: 20rpx auto;
			justify-content: space-between;
			align-items: center;
			border-radius: 10rpx;

			.left {
				width: 148rpx;
				display: flex;
				flex-flow: column nowrap;
				justify-content: center;
				align-items: center;

				image {
					width: 80rpx;
					height: 30rpx;
					margin-bottom: 20rpx;
				}

				.tag {
					background: #FFF1EC;
					color: #FF734F;
					font-size: 24rpx;
					border-radius: 25rpx;
					padding: 10rpx 20rpx;
					box-sizing: border-box;
				}
			}

			.right {
				flex: 1;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20rpx 0 15rpx;

				.item {
					display: flex;
					justify-content: space-between;
					align-items: center;

					image {
						width: 96rpx;
						height: 96rpx;
					}

					.desc {
						height: 96rpx;
						padding-left: 10rpx;

						.title {
							font-size: 24rpx;
							color: #0A0A09;
						}

						.sm {
							color: #AEAEAE;
							font-size: 20rpx;
							margin: 5rpx 0;
						}

						.pricewrapper {
							display: flex;
							justify-content: space-between;

							.price {
								color: #F94949;
								font-size: 20rpx;
								font-weight: bold;
							}

							.zk {
								padding: 5rpx 10rpx;
								box-sizing: border-box;
								border-radius: 15rpx;
								color: #FF734F;
								background: #FFF1EC;
								font-size: 16rpx;
							}
						}
					}
				}
			}
		}

		.smallmenuwrapper {
			width: 100%;
			height: 60rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			margin-top: 20rpx;

			.smallwrapper {
				width: 750rpx;
				height: 60rpx;
				overflow-x: scroll;
				white-space: nowrap;

				.smallitem {
					display: inline-block;
					height: 60rpx;
					line-height: 60rpx;
					padding: 0 30rpx;
					font-size: 28rpx;
					color: #aaa;
				}

				.active {
					color: #FA6964;
					position: relative;
					font-weight: bold;

					&::after {
						content: "";
						width: 30rpx;
						height: 6rpx;
						background: #FA6964;
						position: absolute;
						bottom: 4rpx;
						left: 50%;
						transform: translate(-50%, 100%);
					}
				}
			}
		}

		.guesswrapper {
			margin-top: 20rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 0 30rpx;
			box-sizing: border-box;
			width: 100%;
			height: 60rpx;
			line-height: 60rpx;

			.title {
				font-size: 28rpx;
				font-weight: bold;
			}

			.desc {
				color: #aaa;
				font-size: 24rpx;
				padding-left: 20rpx;
			}
		}

		.listwrapper {
			width: 100%;
			padding: 0 20rpx 20rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
			flex-flow: row wrap;

			.itemwrapper {
				margin-top: 20rpx;
				display: flex;
				flex-flow: column nowrap;
				align-items: center;
				justify-content: space-between;
				width: 50%;
				box-sizing: border-box;

				.pic {
					width: 330rpx;
					height: 320rpx;
					border-radius: 15rpx 15rpx 0 0;
				}

				.descwrapper {
					width: 100%;
					padding: 0 30rpx;
					box-sizing: border-box;

					.namewrapper {
						height: 60rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;
						white-space: nowrap;
						overflow: hidden;
						image {
							width: 48rpx;
							height: 48rpx;
						}
					}

					.pricewrapper {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						height: 30rpx;

						.price {
							color: #F94949;
							font-size: 28rpx;
							font-weight: bold;
						}

						.oldprice {
							color: #aaa;
							text-decoration: line-through;
							font-size: 24rpx;
							margin-left: 15rpx;
						}
					}
				}
			}
		}

	}
</style>